
package org.blaznyoght.subtitles.ui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.JFileChooser;
import javax.swing.JMenuItem;
import javax.swing.filechooser.FileFilter;

import org.blaznyoght.subtitles.model.Collection;
import org.blaznyoght.subtitles.model.SubWriter;

public class SaveActionListener implements ActionListener {
	SwingApplication application;

	public SaveActionListener(SwingApplication swingApplication) {
		setApplication(swingApplication);
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		Collection collection = application.getSubtitles();
		if ((collection.getFile() == null) || (isSaveAsClicked(e))) {
			saveAs(collection);
		}
		else {
			save(collection);
		}
	}

	private void saveAs(Collection collection) {
		JFileChooser chooser = new JFileChooser();
		FileFilter filter = new FileFilter() {
			@Override
			public boolean accept(File file) {
				String name = file.getName();
				String ext = name.split("\\.")[name.split("\\.").length - 1];
				return ext.equalsIgnoreCase("srt");
			}

			@Override
			public String getDescription() {
				return "*.srt";
			}

		};
		chooser.setFileFilter(filter);
		int returnVal = chooser.showSaveDialog(application.getFrame());
		if (returnVal == JFileChooser.APPROVE_OPTION) {
			File subFile = chooser.getSelectedFile();
			collection.setFile(subFile);
			save(collection);
		}
	}

	private boolean isSaveAsClicked(ActionEvent e) {
		boolean ret = false;
		Object source = e.getSource();
		if (source instanceof JMenuItem) {
			JMenuItem item = (JMenuItem) source;
			ret = item.getText().equals("Save as");
		}
		return ret;
	}

	private void save(Collection collection) {
		SubWriter writer = new SubWriter(collection);
		writer.write();
	}

	/**
	 * @return the application
	 */
	public SwingApplication getApplication() {
		return application;
	}

	/**
	 * @param application the application to set
	 */
	public void setApplication(SwingApplication application) {
		this.application = application;
	}

}
